import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Badge, Descriptions, Divider, Form, Spin, Modal, Row, Col } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { Dispatch, connect } from 'umi';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProForm, { ProFormDigit, ProFormDependency, ProFormText } from '@ant-design/pro-form';
import { EditableProTable } from '@ant-design/pro-table';
import { ModalForm } from '@ant-design/pro-form';
import { isNull, inArray } from '@/utils/utils';

interface MyProps {
  dispatch: Dispatch;
  id: string;
  type: string;
  onFinish?: Function;
  onClose: Function;
}


const TableList: React.FC<MyProps> = (props) => {
  const { dispatch, id, type, onFinish, onClose } = props;
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [orderObj, setOrderObj] = useState({});
  const [loading, setLoading] = useState(false);
  const actionRef = useRef<ActionType>();
  const [errorCount, setErrorCount] = useState(0);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [selectedRow, setSelectedRow] = useState([]);
  const [modal, contextHolder] = Modal.useModal();
  const [jy, setJy] = useState(0); // 结余
  
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  type DataSourceType = {
    id: React.Key;
    title?: string;
    decs?: string;
    state?: string;
    created_at?: string;
    children?: DataSourceType[];
  };
  useEffect(() => {
    if(!isNull(id) && isNull(orderObj.order_id)) {
      setLoading(true);
      dispatch({ type: 'order/getInfo', payload: { order_id: id } }).then((res: TableListParams | string) => {
        if (res !== 'error') {
          setOrderObj(res);
          setLoading(false);
          if (!isNull(res.service_price) && parseFloat(res.service_price) > 0) {
            res.order_goods_list.push({
              id: '10086',
              goods_id: '10086',
              goods_name: '配镜服务费',
              goods_total_price: res.service_price,
              goods_num: 1,
            });
          }
          var price = 0;
          var ratio = parseFloat(res.discount_ratio);
          ratio = ratio === 0 ? 0.01 : ratio;
          res.order_goods_list.forEach(element => {
            price = price + (parseFloat(element.goods_total_price) * ratio);
          });
          if (parseFloat(res.discount_ratio) > 0) {
            setJy(parseFloat(parseFloat(res.sett_price) - price));
          }
          form.resetFields();
          actionRef.current && actionRef.current.reload();
        }
      });
    }
  }, []);
  const onSubmit = () => {
    // modal.info({ title: '提示', content: '退款请求已提交至结算中心，退款会原路返回至支付账户', onOk() { onFinish(); }});
    // return;
    console.log('submit', dataSource, editForm.getFieldsError(), form.getFieldValue('total'));
    console.log('selectedRowKeys', selectedRow, editForm.getFieldsValue());
    const refundList = editForm.getFieldsValue(); // 退款列表
    const editErrorList = editForm.getFieldsError();
    const refund_price = parseFloat(form.getFieldValue('total'));
    let result = false;
    for (let i = 0; i < editErrorList.length; i++) {
      const element = editErrorList[i];
      if (!isNull(element.errors)) {
        result = true;
        break;
      }
    }
    if (result) {
      return;
    }
    if (isNull(selectedRow)) {
      message.error('请选择要退款的商品！');
      return;
    }
    console.log('refund_price', refund_price)
    if (refund_price === 0) {
      message.error('请输入正确的退款金额！');
      return;
    }
    if (refund_price > orderObj.maxrefund) {
      message.error(`最多可退${orderObj.maxrefund}元，请修改！`);
      return;
    }
    const list = [];
    selectedRow.forEach(element => {
      if (element.goods_id !== '10086') {
        element.goods_num = refundList[element.goods_id].goods_num;
        element.goods_total_price = refundList[element.goods_id].refundPrice;
        list.push(element);
      }
    });
    console.log('selectedRow-list', list, result);
    // return;
    const params = {
      order_id: id,
      refund_order_goods_list: list,
      refund_price,
      refund_service_price: isNull(refundList['10086']) ? 0 : refundList['10086'].refundPrice
    }
    console.log('params1111', params);
    console.log('modal', modal)
    // modal.info({ title: '123123', content: '456' });
    // return;
    if (!result) {
      // eslint-disable-next-line consistent-return
      return new Promise((resolve) => {
        setLoading(true);
        dispatch({ type: 'order/refund', payload: params }).then((res: TableListParams | string) => {
          setLoading(false);
          resolve(false);
          if (res !== 'error') {
            modal.info({ title: '提示', content: '退款请求已提交至结算中心，退款会原路返回至支付账户', onOk() { onFinish(); }});
            
          }
        });
      });
    } else {
      message.error('请修改')
    }
  };
  const getStatus = (status) => {
    switch (status) {
      case 'C': return <Badge status="processing" text='已开单' />
      case 'W': return <Badge status="processing" text='待支付' />
      case 'P': return <Badge status='success' text='已支付' />
      case 'F': return <Badge status='success' text='已完成' />
      case 'E': return <Badge status='default' text='已作废' />
      default: return '未知状态';
    }
  }
  // 选择行
  const selectRow = (selected: any, selectedRows: any) => {
    // setSelectedDataList(selectedRows);
    console.log('selectedRows', selected, selectedRows)

    const keys = (selectedRows || []).map((item) => item.goods_id)
    setEditableRowKeys(keys);
    (orderObj.order_goods_list || []).map((item, key) => {
      if (isNull(selected) || !inArray(selected, item.goods_id)) {
        dataSource[key] = { ...item, id: item.goods_id };
      }
    });
    setDataSource(dataSource);
    setSelectedRow(selectedRows);
    getTotalPrice();
    actionRef.current && actionRef.current.reload();
    
  };
  // 数量变化、失去焦点
  const countChange = (val, cur, record, myForm, type) => {
    val = parseFloat(val);
    // 输入为正整数，才计算金额
    console.log('aaa', val, Math.sign(val) === -1, Number.isInteger(val), Math.sign(val) === -1 || !Number.isInteger(val))
    if (Math.sign(val) === -1 || !Number.isInteger(val)) {
      if (type === 'change') {
        return;
      }
      val = parseFloat(parseFloat(val).toFixed(0));
    }
    if (Math.sign(val) === 1 && Number.isInteger(val)) {
      const tar = myForm.getFieldsValue()[record.rowKey];
      const dj = parseFloat(orderObj.discount_ratio) === 0 ? 0.01 : parseFloat(cur.goods_price) * parseFloat(orderObj.discount_ratio);
      console.log('blue', dj, val, record.rowIndex, record.rowKey, myForm.getFieldsValue());
      console.log('cur', cur);
      console.log('tar', tar);
      if (tar.goods_num <= cur.goods_num) {
        tar.refundPrice = parseFloat(dj * val).toFixed(2); // 最多可退
        orderObj.order_goods_list[record.rowIndex].maxRefund = tar.refundPrice;
      }
      myForm.setFieldsValue({ [record.rowKey]: tar });
      setOrderObj(orderObj);
      actionRef.current && actionRef.current?.reload();
      getTotalPrice();
    }
  }

  // 计算总金额
  const getTotalPrice = () => {
    setTimeout(() => {
      console.log('getTotalPrice-selectedRowKeys', selectedRow, editForm.getFieldsValue());
      let price = 0;
      let maxprice = 0;
      // eslint-disable-next-line no-restricted-syntax
      for (const key in editForm.getFieldsValue()) {
        const element = editForm.getFieldsValue()[key];
        // console.log('element', element)
        price = parseFloat(price + parseFloat(element.refundPrice));
      }
      selectedRow.forEach(element => {
        maxprice = parseFloat(maxprice + parseFloat(element.goods_price || element.goods_total_price));
      });
      console.log('price11111', maxprice);
      if (parseFloat(price) > 0) {
        form.setFieldsValue({ total: price.toFixed(2) });
        orderObj.maxrefund = parseFloat(price);
        setOrderObj(orderObj);
      }
    }, 100);
  }

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '品牌',
      dataIndex: 'brand_name',
      align: 'center',
      width: 150,
      editable: false,
    },
    {
      title: '编号',
      dataIndex: 'goods_id',
      align: 'center',
      editable: false,
      width: 100,
    },
    {
      title: '名称',
      dataIndex: 'goods_name',
      align: 'center',
      editable: false,
      width: 150,
    },
    {
      title: '规格',
      dataIndex: 'specs_name',
      width: '15%',
      align: 'center',
      editable: false,
      width: 150,
    },
    {
      title: '需退款数量',
      dataIndex: 'goods_num',
      valueType: 'digit',
      align: 'right',
      width: 110,
      fieldProps: {
        precision: 0,
        min: 1,
      },
      editable: (e, e1) => e1.goods_id !== '10086',
      formItemProps: (myForm, record) => {
        // console.log('数量', form.getFieldsValue());
        // console.log('record', record);
        const cur = orderObj.order_goods_list[record.rowIndex];
        return {
          rules: [{ required: true, message: '此项为必填项' },
            { validator: (e, val) => {
              if (val < 1 || val > cur.goods_num) {
                setErrorCount(errorCount + 1);
                return Promise.reject(new Error(`最多可退${cur.goods_num}!`)); 
              } else {
                setErrorCount(errorCount - 1);
              }
              return Promise.resolve();
            }, message: `最多可退${cur.goods_num}!`},
          ],
          onBlur: (e) => countChange(e.target.value, cur, record, myForm, 'blur'),
          onChange: (e) => countChange(e.target.value, cur, record, myForm, 'change'),
        };
      },
    },
    {
      title: '支付金额',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      width: 130,
      editable: false,
      renderText: (val, record, index) => {
        var price = 0;
        if (parseFloat(orderObj.discount_ratio) === 0) {
          price = parseFloat(record.goods_num * 0.01).toFixed(2);
        } else {
          price = parseFloat(parseFloat(record.goods_total_price) * parseFloat(orderObj.discount_ratio)).toFixed(2);
        }
        if (index === orderObj.order_goods_list.length - 1) {
          console.log('aaa', price, jy);
          price = parseFloat(parseFloat(price) + jy).toFixed(2);
        }
        return price;
      },
    },
    {
      title: '退款金额',
      dataIndex: 'refundPrice',
      valueType: 'money',
      align: 'right',
      width: 130,
      renderText: (val, record, index) => {
        console.log('index', index);
        var price = 0;
        if (parseFloat(orderObj.discount_ratio) === 0) {
          price = parseFloat(record.goods_num * 0.01).toFixed(2);
        } else {
          price = parseFloat(parseFloat(record.goods_total_price) * parseFloat(orderObj.discount_ratio)).toFixed(2);
        }
        if (index === orderObj.order_goods_list.length - 1) {
          price = parseFloat(parseFloat(price) + jy).toFixed(2);
        }
        return price;
      },
      formItemProps: (form, record) => {
        const cur = orderObj.order_goods_list[record.rowIndex];
        console.log('cur', cur);
        let max = 0;
        if (parseFloat(orderObj.discount_ratio) === 0) {
          max = parseFloat(cur.goods_num * 0.01).toFixed(2);
        } else {
          max = parseFloat(parseFloat(cur.goods_total_price) * parseFloat(orderObj.discount_ratio)).toFixed(2);
        }
        if (record.rowIndex === orderObj.order_goods_list.length - 1) {
          max = parseFloat(parseFloat(max) + jy).toFixed(2);
        }
        return {
          rules: [{ required: true, message: '此项为必填项' },
            { validator: (e, val) => {
              if (val > parseFloat(cur.maxRefund || parseFloat(max))) {
                return Promise.reject(new Error('111')); 
              }
              return Promise.resolve();
            }, message: `最多可退${cur.maxRefund || max}元`},
            { validator: (e, val) => {
              if (val <= 0) {
                return Promise.reject(new Error('111')); 
              }
              return Promise.resolve();
            }, message: `退款金额不能为0`},
          ],
          onBlur: e => getTotalPrice(),
          onChange: e => getTotalPrice()
        };
      },
    },
  ];
  console.log('结余', jy);
  return (
    <ModalForm
      form={form}
      title='退款'
      width={window.innerWidth > 1370 ? '70%' : "90%"}
      visible
      layout='horizontal'
      modalProps={{
        onCancel: () => onClose(),
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: '确认退款',
          resetText: '取消',
        },
      }}
      {...formItemLayout}
      initialValues={{
        ...orderObj
      }}
      onFinish={async() => await onSubmit()}
    >
      <Spin spinning={loading}>
        <Descriptions size="small" column={2}>
          <Descriptions.Item label="患者姓名">{orderObj.patient_name}</Descriptions.Item>
          <Descriptions.Item label="患者身份证">{orderObj.identity_no}</Descriptions.Item>
        </Descriptions>
        <Divider style={{ margin: '10px 0 0' }} />
        <div className='org' style={{ margin: '10px 0' }}>请先勾选需要退款的商品</div>
        <EditableProTable<DataSourceType>
          rowKey="id"
          size='small'
          bordered
          columns={columns}
          actionRef={actionRef}
          loading={loading}
          className='dialogTable'
          request={async () => ({
            data: () => orderObj.order_goods_list.map((item) => { return {...item, id: item.goods_id} }),
            success: true
          })}
          search={false}
          options={false}
          pagination={false}
          recordCreatorProps={false}
          value={dataSource}
          onChange={setDataSource}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: false,
            onChange: selectRow
          }}
          tableAlertRender={false}
          editable={{
            form: editForm,
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
        <Divider />
        <Row>
          <Col span={8}>
            <ProFormText
              label="折扣比例"
              name="discount_ratio"
              readonly
              labelCol={{
                xl: { span: 8 },
                xxl: { span: 5 },
              }}
            />
          </Col>
          <Col span={8}>
            <ProFormDigit
              label="退款总金额"
              name="total"
              min={0}
              max={99999999}
              initialValue={0.00}
              fieldProps={{ precision: 2 }}
              labelCol={{
                xl: { span: 8 },
                xxl: { span: 6 },
              }}
            />
          </Col>
        </Row>
      </Spin>
      {contextHolder}
    </ModalForm>
  );
};

export default connect()(TableList);
